<template>
  <div class="echart" ref="myChart"></div>
</template>
<script>
import * as echarts from 'echarts';

export default {
  props: {
    options: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      myChart: null,
    };
  },
  watch: {
    options: {
      handler() {
        this.initEchart();
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    // 初始化
    initEchart() {

      this.$nextTick(() => {

        if (this.myChart !== null && this.myChart !== '' && this.myChart !== undefined) {
          this.myChart.clear();
        }
        this.myChart = echarts.init(this.$refs.myChart);
        // 渲染前销毁事件
        this.myChart.off('click');
        this.myChart.off('mouseout');
        this.myChart.off('mouseover');

        this.myChart.setOption(this.options);
        this.myChart.on('click', (params) => {
          this.$emit('echartClick', params, this.options);
        });
        this.myChart.on('mouseout', (params) => {
          this.$emit('echartMouseout', params);
        });
        this.myChart.on('mouseover', (params) => {
          this.$emit('echartMouseover', params);
        });
      });
    },
  },
  mounted() {
    // 页面放大缩小时
    this.$nextTick(() => {
      window.addEventListener('resize', () => {
        this.myChart.resize();
      });
    });
  },
  beforeDestroy() {
    window.removeEventListener('resize', () => {
      this.myChart.resize();
    });
  },
};
</script>
<style lang="less" scoped>
.echart {
  width: 100%;
  height: 100%;
}
</style>
